<template>
    <div class="app-container">
        <!-- 逻辑层 -->
        <BookInfo ref="infoRef" @flush="loadData" />
        <!-- 逻辑层 -->

        <!-- 筛选 -->
        <div v-if="filterState">
            <el-form :inline="true" :model="queryData">
                <el-form-item label="书籍名称">
                    <el-input placeholder="请输入书籍名称" v-model="queryData.name" />
                </el-form-item>
                <el-form-item label="书籍类别">
                    <el-select v-model="queryData.typesList" multiple placeholder="选择书籍类型" style="width: 240px">
                        <el-option v-for="item in bookTypesOptions" :key="item.id" :label="item.typesName"
                            :value="Number(item.id)">
                            <div class="flex items-center">
                                {{ item.typesName }}
                            </div>
                        </el-option>

                        <template #tag>
                            <el-tag v-for="types in queryData.typesList" :key="types" />
                        </template>
                    </el-select>
                </el-form-item>

                <el-form-item label="活动日期" v-show="isExpand">
                    <el-date-picker v-model="queryDate" type="daterange" value-format="YYYY-MM-DD HH:mm:ss"
                        format="YYYY-MM-DD HH:mm:ss" range-separator="到" start-placeholder="开始日期"
                        end-placeholder="结束日期" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadData"> <span class="iconfont icon-sousuo"></span>搜索
                    </el-button>
                    <el-button type="default" @click="resetQuery"> 重置 </el-button>
                    <el-button type="primary" link @click="isExpand = !isExpand">
                        {{ isExpand ? '收起' : '展开' }}
                        <el-icon>
                            <ArrowUp v-if="isExpand" />
                            <ArrowDown v-else />
                        </el-icon>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 筛选 -->
        <!-- 内容 -->
        <!-- 按钮组 -->
        <el-row>
            <el-col :span="12">
                <el-button type="primary" @click="onAdd">
                    <span class="iconfont icon-jiahao"></span>添加
                </el-button>
                <el-button type="danger" :disabled="!ids.length" @click="onDeleteMulti()">
                    <span class="iconfont icon-shanchu"></span>删除
                </el-button>
                <el-button type="waring" @click="exportExcelFn">
                    <span class="iconfont icon-daochu"></span>导出
                </el-button>
                <el-button type="waring" @click="handleImport">
                    <span class="iconfont icon-daoru"></span>导入
                </el-button>
            </el-col>

            <el-col :span="12" style="text-align: right">
                <el-button circle @click="filterState = !filterState">
                    <span class="iconfont icon-sousuo"></span>
                </el-button>
                <el-button circle>
                    <span class="iconfont icon-shuaxin"></span>
                </el-button>
            </el-col>
        </el-row>
        <!-- 按钮组 -->
        <!-- 表格 -->
        <el-table :data="tableData.rows" :border="true" @selection-change="onSelectionChange">
            <el-table-column type="selection" align="center" fixed="left"></el-table-column>
            <el-table-column label="序号" prop="id" align="center"></el-table-column>
            <el-table-column label="书籍名称" prop="name" align="center"></el-table-column>
            <el-table-column label="书籍类型" prop="types" align="center">
                <template #default="scoped">
                    <el-tag  effect="dark" round>
                        {{ getBookTypesName(scoped.row) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="书籍简介" prop="remark" align="center"></el-table-column>
            <el-table-column label="书籍评分" prop="score" align="center"></el-table-column>
            <!-- <el-table-column label="收藏数" prop="favors" align="center"></el-table-column> -->
            <el-table-column label="创建人" prop="createBy" align="center"></el-table-column>
            <!-- <el-table-column label="已报名人数" prop="nums" align="center"></el-table-column> -->
            <el-table-column label="创建时间" prop="createTime" align="center" width="200">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120" fixed="right">
                <template #default="scoped">
                    <el-button type="primary" link size="small" @click="onEdit(scoped.row)">
                        <span class="iconfont icon-bianji"></span>修改
                    </el-button>
                    <el-button type="primary" link size="small" @click="onDelete(scoped.row)">
                        <span class="iconfont icon-shanchu"></span>删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 表格 -->
        <!-- 分页 当前页码 current-page属性 需要与 传回数据-->
        <el-pagination v-model:current-page="queryData.pageNum" v-model:page-size="queryData.pageSize"
            :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.total" @size-change="loadData" @current-change="loadData" />
        <!-- 分页 -->
        <!-- 内容 -->
    </div>




    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
                <div class="el-upload__tip text-center">
                    <div class="el-upload__tip">
                        <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                    </div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                        @click="importTemplate">下载模板</el-link>
                </div>
            </template>
        </el-upload>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="books">
import BookInfo from './book_info.vue'
import { listBook, getInfoForAddAndUpdate, delBook, exportExcel } from '@/api/book/book.js'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from "@/utils/auth";
// 获取vue上下文
const { proxy } = getCurrentInstance();
// 表单状态
const filterState = ref(true)
// 表单数据
const isExpand = ref(false)
const queryDate = ref([])
onMounted(() => {
    loadData()
})
// 增删改请求体
const formData = ref({
    name: '',
    sdate: null,
    edate: null
})
// 查询请求体
const queryData = ref({
    pageNum: 1,
    pageSize: 2,
    typesList: [],
    name: '',
    createTimeBegin: null,
    createTimeEnd: null
})
/** 重置按钮操作 */
function resetQuery() {
    queryDate.value = []
    queryData.value.name = ''
    queryData.value.createTimeBegin = null
    queryData.value.createTimeEnd = null
    queryData.value.typesList = []

    queryData.value.pageNum = 1;
    loadData();
};

const tableData = ref({})
const bookTypesOptions = ref([])
const loadData = async () => {
    console.log("dates", queryDate.value);
    //请求 查询 接口
    queryData.value.createTimeBegin = queryDate.value[0]
    queryData.value.createTimeEnd = queryDate.value[1];
    const r = await listBook(queryData.value)

    const dict_r = await getInfoForAddAndUpdate()
    tableData.value = r
    bookTypesOptions.value = dict_r.book_types

}
/** 导出按钮操作 */
const exportExcelFn = async () => {

    proxy.download("/test/book/export", {
        ...queryData.value,
    }, `book_${new Date().getTime()}.xlsx`);

}

const open = ref(false);
/*** 用户导入参数 */
const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/test/book/importData"
});
/** 导入按钮操作 */
function handleImport() {
    upload.title = "用户导入";
    upload.open = true;
}
function submitFileForm() {
    const result = proxy.$refs["uploadRef"].submit()
    console.log(JSON.stringify(result));
}
const getBookTypesName = (row) => {
    const matchingType = Object.values(bookTypesOptions.value).find((type) => type.id === row.types.toString());
    return matchingType.typesName
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    loadData()
};


// 批量选择
let ids = ref([])
const onSelectionChange = (val) => {
    ids.value = val
}

// 用户删除
const onDelete = (row) => {
    ElMessageBox.confirm('确定删除该条数据吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        //请求接口 删除数据
        let r = await delBook({ id: [row.id] })
        if (r.code == 200) {
            ElMessage({ type: 'success', message: '删除成功' })
        } else {
            ElMessage({ type: 'info', message: r.data })
        }
    }).catch(() => {
        ElMessage({
            type: 'info', message: '删除失败'
        })
    }).finally(() => {
        loadData()
    })
}
const onDeleteMulti = () => {
    ElMessageBox.confirm('确定删除这些数据吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        //请求接口 删除数据
        if (ids.value.length > 0) {

            let ids_result = ids.value.map(item => item.id);
            let r = await delBook({ id: [ids_result] })
            if (r.code == 200) {
                ElMessage({ type: 'success', message: '删除成功' })
            } else {
                ElMessage({ type: 'info', message: r.data })
            }
        }
    }).catch(() => {
        ElMessage({
            type: 'info', message: '删除失败'
        })
    }).finally(() => {
        loadData()
    })
}


// 弹窗对象
const infoRef = ref()

const onAdd = () => {
    reset()
    // 给弹窗名字中的 state 赋值 为true 开启弹窗
    infoRef.value.state = true
    console.log("add");
    getInfoForAddAndUpdate().then(r => {
        infoRef.value.bookTypesOptions = r.book_types
    })

}
const onEdit = (row) => {
    reset()
    console.log("row" + JSON.stringify(row));
    // 之所以能调用 子组件的 state isEdit formData 属性，
    // 因为 在子组件中 使用defineExpose暴露了这些属性，否则无法调用

    // 给弹窗名字中的 state 赋值 为true 开启弹窗
    infoRef.value.state = true

    if (row) {
        getInfoForAddAndUpdate(row.id).then(r => {
            console.log("onEditbookTypesOptions", JSON.stringify(r.book_types));
            infoRef.value.bookTypesOptions = r.book_types
            // 若这行不为空则 开启弹窗的编辑模式 并赋值
            infoRef.value.isEdit = true
            infoRef.value.formData = row
            console.log("formData111" + JSON.stringify(infoRef.value.formData));
        })
    }
}

/** 重置操作表单 */
function reset() {
    infoRef.value.formData = {
        name: undefined,
        types: undefined,
        remark: undefined,
        score: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
    };
    proxy.resetForm("userRef");
};
</script>